﻿// -----------------------------------------------------------------------
// <copyright file="ContentProviderAuthenticationService.cs" company="Zen Design Corp">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Zen.BlackBerry.Subscription.Auth
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;
	using System.Security.Principal;
	using System.Web.Security;

	/// <summary>
	/// Default implementation of <see cref="IContentProviderAuthenticationService"/>
	/// that delegates authentication to the ASP.NET membership system.
	/// </summary>
	public class ContentProviderAuthenticationService : IContentProviderAuthenticationService
	{
		#region IContentProviderAuthenticationService Members

		/// <summary>
		/// Authenticates a subscriber with the content provider based on the
		/// information passed in.
		/// </summary>
		/// <param name="request">The request.</param>
		/// <returns>
		/// A <see cref="T:IPrincipal"/> containing the results of a successful
		/// authentication.
		/// </returns>
		/// <remarks>
		/// Important note: An implementation of this method should ONLY
		/// contain business logic relating to the authentication of a
		/// subscriber. It should not contain any form of subscription business
		/// logic.
		/// </remarks>
		public IPrincipal AuthenticateSubscriber(BaseAuthenticationRequest request)
		{
			AuthenticationRequest basicAuth = (AuthenticationRequest)request;
			if (!FormsAuthentication.Authenticate(basicAuth.UserName, basicAuth.Password))
			{
				return null;
			}

			// Create forms identity using an non-persistent ticket
			FormsAuthenticationTicket ticket = 
				new FormsAuthenticationTicket (basicAuth.UserName, false, 10);
			FormsIdentity identity = new FormsIdentity(ticket);

			// Add user roles (if any) for completeness...
			string[] roles = Roles.GetRolesForUser(basicAuth.UserName);

			// Return a principal object
			return new GenericPrincipal(identity, roles);
		}

		#endregion
	}
}
